﻿using Learun.Application.TwoDevelopment.ZZDT_EC;
using Learun.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace Learun.Application.Web.AppApi
{
    /// <summary>
    /// 关联关系的接口（By YuXH）。只需要给rel data的操作，rel type的操作放到mvc的API即可，暂时不需要给插件端开放
    /// </summary>
    [RoutePrefix("api/RelApi")]
    [HandlerApiLogin(FilterMode.Ignore)]
    public class RelApiController : WebApiControllerBase
    {
        #region 模块对象
        private ec_reltypeIBLL ec_reltypeIBLL = new ec_reltypeBLL();
        private ec_enginedata_relIBLL ec_relDataBLL = new ec_enginedata_relBLL();
        #endregion

        #region refDef本身，只给查询，编辑放在网页端里
        /// <summary>
        /// 根据关联关系的名字拿关联关系的Id
        /// </summary>
        /// <param name="RelName"></param>
        /// <param name="projId"></param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetRelDefByName(string RelName, string projId)
        {
            var data = ec_reltypeIBLL.GetList("{\"ProjectId\":\"" + projId + "\", \"RelTypeName\": \"" + RelName + "\"}").FirstOrDefault();
            return Success(data);
        }

        /// <summary>
        /// 所有Rel
        /// </summary>
        /// <param name="RelName"></param>
        /// <param name="projId"></param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetRelDefs(string projId)
        {
            var data = ec_reltypeIBLL.GetList("{\"ProjectId\":\"" + projId + "\"}");
            return Success(data);
        }
        #endregion

        #region engineData_rel
        /// <summary>
        /// 增加 对象和对象之间的关系。(BY YUXH)
        /// 请求的Body中带上Json格式的ec_enginedata_relEntity数据集合（End2IDs里放多个）
        /// </summary>
        /// <param name="ProjectId"></param>
        /// <returns></returns>
        [HttpPost]
        [HandlerApiLogin(FilterMode.Enforce)]
        public IHttpActionResult SaveRelDataBatch(string ProjectId)
        {
            var asyncContent = Request.Content.ReadAsStringAsync().Result;
            try
            {
                var entityCol = asyncContent.ToObject<IEnumerable<ec_enginedata_relEntity>>();

                foreach (var relData in entityCol)
                {
                    if (relData.End2IDs == null || relData.End2IDs.Count == 0)
                    {
                        relData.End2IDs = new List<string>
                        {
                            relData.RelEngineData2ID
                        };
                    }
                    ec_relDataBLL.SaveEntitys(ProjectId, relData.RelTypeID, relData.RelEngineData1ID, relData.End2IDs);

                }



                return Success("创建成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }

        }

        /// <summary>
        /// 根据主键，删除某条关联关系
        /// </summary>
        /// <param name="ProjectId"></param>
        /// <param name="RelDataId"></param>
        /// <returns></returns>
        [HttpGet]
        [HandlerApiLogin(FilterMode.Enforce)]
        public IHttpActionResult RemoveRelData(string ProjectId, string RelDataId)
        {

            ec_relDataBLL.DeleteEntity(ProjectId, RelDataId);
            return Success("delete成功");
        }


        /// <summary>
        /// 主力查询
        /// </summary>
        /// <param name="ProjectId"></param>
        /// <param name="RelTypeId"></param>
        /// <param name="ID1">1端的ID</param>
        /// <param name="seq"></param>
        /// <returns></returns>
        [HttpGet]
        [HandlerApiLogin(FilterMode.Ignore)]
        public IHttpActionResult GetRelCollection(string ProjectId, string RelTypeId, string ID1 = "", int seq = 0)
        {
            if (!string.IsNullOrEmpty(ID1))
            {
                //查单一记录
                var res = ec_relDataBLL.GetList("{ProjectId:\"" + ProjectId + "\",RelTypeID:\"" + RelTypeId + "\",RelEngineDataID:\"" + ID1 + "\"}");
                return Success(res);
            }
            else
            {
                var res = ec_relDataBLL.GetList("{ProjectId:\"" + ProjectId + "\",RelTypeID:\"" + RelTypeId + "\"}");
                return Success(res);
            }
        }
        #endregion


        #region Cable连接关系
        /// <summary>
        /// 查询电缆两侧的连接关系(BY YUXH)
        /// </summary>
        /// <param name="ProjectId"></param>
        /// <param name="IDs">集合（图纸id，电缆句柄）</param>
        /// <returns></returns>
        [HttpPost]
        [HandlerApiLogin(FilterMode.Enforce)]
        public IHttpActionResult GetCableConn(string ProjectId, [FromBody] List<CableConnRel> CablePixelIDs)
        {
            if (CablePixelIDs == null) { return Success(""); }
            var RelTypeServ = new ec_reltypeBLL();
            var relBll = new ec_enginedata_relBLL();
            //relType是不是有
            var RelTypeID = RelTypeServ.GetList("{\"ProjectId\":\"" + ProjectId + "\", \"RelType\": \"" + (int)enum_RelType.设备_电缆 + "\"}").Select(x => x.RelTypeID).FirstOrDefault();

            if (RelTypeID == null || RelTypeID.Count() == 0)
            {
                return Fail($"项目的关联类型中，找不到“设备_电缆”,其RelType应该为0。");
            }
            var res = new List<CableConnRes>();
            //var asyncContent = Request.Content.ReadAsStringAsync().Result;
            try
            {

                //var relDataCol = asyncContent.ToObject<IEnumerable<CableConnRel>>();

                foreach (var CablePixelID in CablePixelIDs)
                {

                    res.Add(relBll.GetCableConn(CablePixelID, ProjectId));

                }



                return Success(res);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 查询电缆整个链路上的连接(BY YUXH)
        /// </summary>
        /// <param name="ProjectId"></param>
        /// <param name="CablePixelIDs">集合（图纸id，电缆句柄）</param>
        /// <returns></returns>
        [HttpPost]
        [HandlerApiLogin(FilterMode.Enforce)]
        public IHttpActionResult GetCableWay(string ProjectId, [FromBody] List<CableConnRel> CablePixelIDs)
        {
            if (CablePixelIDs == null) { return Success(""); }
            //serv
            var pixelServ = new ec_enginedata_pixelService();
            var RelTypeServ = new ec_reltypeBLL();
            //relType是不是有
            var RelTypeID = RelTypeServ.GetList("{\"ProjectId\":\"" + ProjectId + "\", \"RelType\": \"" + (int)enum_RelType.设备_电缆 + "\"}").Select(x => x.RelTypeID).FirstOrDefault();

            if (RelTypeID == null || RelTypeID.Count() == 0)
            {
                return Fail($"项目的关联类型中，找不到“设备_电缆”,其RelType应该为0。");
            }
            var res = new LinkedList<object>();
            //var asyncContent = Request.Content.ReadAsStringAsync().Result;
            try
            {

                //var relDataCol = asyncContent.ToObject<IEnumerable<CableConnRel>>();

                foreach (var CablePixelID in CablePixelIDs)
                {
                    var CableWay = new LinkedList<object>();
                    //根据句柄和图纸，先把工程id查出来先
                    var drawingID = CablePixelID.DrawingID;
                    var pixelID = CablePixelID.CablePixelID;
                    var EngineDataIDs = pixelServ.GetList("{\"ProjectId\":\"" + ProjectId + "\",\"PixelCode\":\"" + pixelID + "\",\"DrawingFileID\":\"" + drawingID + "\"}").Distinct();
                    if (EngineDataIDs != null && EngineDataIDs.Count() == 1)
                    {
                        var engineDataPixel = EngineDataIDs.First();
                        var CableID = engineDataPixel.EngineDataID;
                        ec_enginedata_relEntity End1;
                        ec_enginedata_relEntity End2;
                        string End1ID = "", End1Type = "", End1Tag = "";
                        string End2ID = "", End2Type = "", End2Tag = "";
                        //查单一记录
                        var existRel = ec_relDataBLL.GetList("{ProjectId:\"" + ProjectId + "\",RelType:\"" + (int)enum_RelType.设备_电缆 + "\",RelEngineDataID:\"" + CableID + "\"}");
                        if (existRel.Count(x => x.RelEngineData1ID == CableID) == 1) // 电缆在end1，代表该行记录的end2 是 设备
                        {
                            End2 = existRel.Where(x => x.RelEngineData1ID == CableID).FirstOrDefault();
                            End2ID = End2.RelEngineData2ID;
                            End2Type = End2.Type2;
                            End2Tag = End2.TagNumber2;
                        }
                        if (existRel.Count(x => x.RelEngineData2ID == CableID) == 1) // 电缆在end2，代表该行记录的end1 是 设备
                        {
                            End1 = existRel.Where(x => x.RelEngineData2ID == CableID).FirstOrDefault();
                            End1ID = End1.RelEngineData1ID;
                            End1Type = End1.Type1;
                            End1Tag = End1.TagNumber1;
                        }

                        CableWay.AddLast(
                            new
                            {
                                ObjectTypeName = engineDataPixel.ObjectTypeName,
                                TagNumber = engineDataPixel.TagNumber,
                                ID = CableID,

                            }); //电缆自己
                                //上游去找
                        while (End1ID != "") //条件满足就循环，不满足跳出
                        {
                            var obj = new
                            {
                                ObjectTypeName = End1Type,
                                TagNumber = End1Tag,
                                ID = End1ID,
                            };
                            if (CableWay.Contains(obj))
                            {
                                End1ID = "";
                                continue; //避免回路
                            }
                            else
                            {
                                CableWay.AddFirst(obj); //上游
                            }
                            //查单一记录
                            existRel = ec_relDataBLL.GetList("{ProjectId:\"" + ProjectId + "\",RelType:\"" + (int)enum_RelType.设备_电缆 + "\",RelEngineDataID:\"" + End1ID + "\"}");

                            if (existRel.Count(x => x.RelEngineData2ID == End1ID) == 1) // 在end2，代表该行记录的end1 是 再上游的
                            {
                                End1 = existRel.Where(x => x.RelEngineData2ID == End1ID).FirstOrDefault();
                                End1ID = End1.RelEngineData1ID;
                                End1Type = End1.Type1;
                                End1Tag = End1.TagNumber1;
                            }
                            else if (existRel.Count(x => x.RelEngineData2ID == End1ID) == 0)
                            {
                                End1 = null;
                                End1ID = "";//没有上游了 可以停下了
                            }
                            //else if (existRel.Count(x => x.RelEngineData2ID == End1) > 1)
                            //{
                            //暂时不考虑
                            //}
                        }


                        //下游去找
                        while (End2ID != "") //条件满足就循环，不满足跳出
                        {
                            var obj = new
                            {
                                ObjectTypeName = End2Type,
                                TagNumber = End2Tag,
                                ID = End2ID,
                            };
                            if (CableWay.Contains(obj))
                            {
                                End2ID = "";
                                continue; //避免回路
                            }
                            else
                            {
                                CableWay.AddLast(obj); //下游
                            }

                            //查单一记录
                            existRel = ec_relDataBLL.GetList("{ProjectId:\"" + ProjectId + "\",RelType:\"" + (int)enum_RelType.设备_电缆 + "\",RelEngineDataID:\"" + End2ID + "\"}");
                            if (existRel.Count(x => x.RelEngineData1ID == End2ID) == 1) // 在end2，代表该行记录的end1 是 再上游的
                            {
                                End2 = existRel.Where(x => x.RelEngineData1ID == End2ID).FirstOrDefault();
                                End2ID = End2.RelEngineData2ID;
                                End2Type = End2.Type2;
                                End2Tag = End2.TagNumber2;
                            }
                            else if (existRel.Count(x => x.RelEngineData1ID == End2ID) == 0)
                            {
                                End2 = null;
                                End2ID = "";//没有上游了 可以停下了
                            }
                            //else if (existRel.Count(x => x.RelEngineData2ID == End1) > 1)
                            //{
                            //暂时不考虑
                            //}
                        }

                    }
                    else
                    {
                        return Fail($"根据句柄{pixelID}查询出的ec_enginedata_pixel有多个ID记录。");
                    }
                    res.AddLast(CableWay);

                }
                return Success(res);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }
        /// <summary>
        /// 查询电缆整个链路上的连接(BY YUXH)
        /// </summary>
        /// <param name="ProjectId"></param>
        /// <param name="CablePixelIDs">集合（图纸id，电缆句柄）</param>
        /// <returns></returns>
        [HttpPost]
        [HandlerApiLogin(FilterMode.Enforce)]
        public IHttpActionResult GetCableAllWay(string ProjectId, [FromBody] List<CableConnRel> CablePixelIDs)
        {
            if (CablePixelIDs == null) { return Success(""); }
            var relServ = new ec_enginedata_relService();
            var res = relServ.GetCableWay(ProjectId, CablePixelIDs);
            return Success(res);
        }
        /// <summary>
        /// 保存电缆连接关系（专门），不走SaveRelDataBatch。创建电缆时传2个连接，修改电缆连接时传1个
        /// </summary>
        /// <param name="ProjectId"></param>
        /// <param name="relDataCol">集合（图纸id，电缆句柄，设备句柄，是否起始）</param>
        /// <returns></returns>
        [HttpPost]
        [HandlerApiLogin(FilterMode.Enforce)]
        public IHttpActionResult SaveCableConn(string ProjectId, [FromBody] IEnumerable<CableConnRel> relDataCol)
        {
            //起始设备 终止设备的属性定义

            if (relDataCol == null) { return Success(""); }
            //serv
            var pixelServ = new ec_enginedata_pixelService();
            var RelTypeServ = new ec_reltypeBLL();
            //relType是不是有
            var RelTypeID = RelTypeServ.GetList("{\"ProjectId\":\"" + ProjectId + "\", \"RelType\": \"" + (int)enum_RelType.设备_电缆 + "\"}").Select(x => x.RelTypeID).FirstOrDefault();

            if (RelTypeID == null || RelTypeID.Count() == 0)
            {
                return Fail($"项目的关联类型中，找不到“设备_电缆”,其RelType应该为0。");
            }

            //var asyncContent = Request.Content.ReadAsStringAsync().Result;
            try
            {

                //var relDataCol = asyncContent.ToObject<IEnumerable<CableConnRel>>();
                foreach (var relData in relDataCol.Where(x => x.NeedRemove == true))
                {
                    if (string.IsNullOrEmpty(relData.TagPixelID) || string.IsNullOrEmpty(relData.CablePixelID))
                    {
                        return Fail($"位号图元 或 电缆图元的句柄不能为空。");
                    }
                    //根据句柄和图纸，先把工程id查出来先
                    //获取工程数据图元数据
                    var EngineDataIDs = pixelServ.GetList("{\"ProjectId\":\"" + ProjectId + "\",\"PixelCode\":\"" + relData.TagPixelID + "\",\"DrawingFileID\":\"" + relData.DrawingID + "\"}").
                                                            Select(x => x.EngineDataID).Distinct();
                    var CableIDs = pixelServ.GetList("{\"ProjectId\":\"" + ProjectId + "\",\"PixelCode\":\"" + relData.CablePixelID + "\",\"DrawingFileID\":\"" + relData.DrawingID + "\"}").
                                                           Select(x => x.EngineDataID).Distinct();
                    if (EngineDataIDs != null && EngineDataIDs.Count() == 1 && CableIDs != null && CableIDs.Count() == 1)
                    {
                        var TagID = EngineDataIDs.First();
                        var CableID = CableIDs.First();
                        if (relData.IsEnd1)
                        {
                            ec_relDataBLL.DeleteEntity(ProjectId, RelTypeID, "", CableID);
                        }
                        else
                        {
                            ec_relDataBLL.DeleteEntity(ProjectId, RelTypeID, CableID, "");
                        }

                    }
                    else
                    {
                        return Fail($"根据句柄{relData.CablePixelID} 和 {relData.TagPixelID}，查询出的ec_enginedata_pixel，有多个工程ID记录。");
                    }
                }
                foreach (var relData in relDataCol.Where(x => x.NeedRemove == false))
                {
                    //根据句柄和图纸，先把工程id查出来先
                    //获取工程数据图元数据
                    var EngineDataIDs = pixelServ.GetList("{\"ProjectId\":\"" + ProjectId + "\",\"PixelCode\":\"" + relData.TagPixelID + "\",\"DrawingFileID\":\"" + relData.DrawingID + "\"}").
                                                            Select(x => x.EngineDataID).Distinct();
                    var CableIDs = pixelServ.GetList("{\"ProjectId\":\"" + ProjectId + "\",\"PixelCode\":\"" + relData.CablePixelID + "\",\"DrawingFileID\":\"" + relData.DrawingID + "\"}").
                                                           Select(x => x.EngineDataID).Distinct();
                    if (EngineDataIDs != null && EngineDataIDs.Count() == 1 && CableIDs != null && CableIDs.Count() == 1)
                    {
                        var TagID = EngineDataIDs.First();
                        var CableID = CableIDs.First();
                        if (relData.IsEnd1)
                        {
                            ec_relDataBLL.SaveEntitys(ProjectId, RelTypeID, new List<string> { TagID }, CableID, true);
                        }
                        else
                        {
                            ec_relDataBLL.SaveEntitys(ProjectId, RelTypeID, CableID, new List<string> { TagID }, true);
                        }

                    }
                    else
                    {
                        if (EngineDataIDs == null || EngineDataIDs.Count() == 0)
                        {
                            return Fail($"根据句柄 {relData.TagPixelID} 查询出的工程ID,只有0个ID记录。");

                        }
                        if (CableIDs == null || CableIDs.Count() == 0)
                        {
                            return Fail($"根据句柄 {relData.CablePixelID} 查询出的工程ID,只有0个ID记录。");
                        }
                        if (EngineDataIDs != null || EngineDataIDs.Count() > 1)
                        {
                            return Fail($"根据句柄 {relData.TagPixelID} 查询出的工程ID,多于1个记录，共有{EngineDataIDs.Count()}个。");
                        }
                        if (CableIDs != null || CableIDs.Count() > 1)
                        {
                            return Fail($"根据句柄 {relData.CablePixelID} 查询出的工程ID,多于1个记录，共有{CableIDs.Count()}个。");
                        }
                    }


                }



                return Success("创建成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }

        }
        #endregion
    }
}